package com.thinkerwu.learn.core.utils;

import org.hibernate.validator.HibernateValidator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Iterator;
import java.util.Set;

/**
 * 接口入参数据校验工具类.
 * 使用hibernate-validator进行校验.
 * 其中加入自定义的校验器
 *
 * @author Thinker Wu
 * @date 2018年10月19日-17时08分
 */
@Scope("singleton")
@Component
public class ValidationUtil {

    private static final Logger logger = LoggerFactory.getLogger(ValidationUtil.class);


    /**
     * 使用hibernate的注解来进行验证
     */
    private static Validator validator = Validation
            .byProvider(HibernateValidator.class).configure().failFast(false).buildValidatorFactory().getValidator();

    /**
     * 表单校验器
     *
     * @param obj
     */
    public static <T> String defaultValidate(T obj) {
        logger.info("开始对类型{}进行校验", obj.getClass());
        Set<ConstraintViolation<T>> constraintViolations = validator.validate(obj);
        StringBuffer errMessage = new StringBuffer();
        if (constraintViolations.size() > 0) {
            Iterator<ConstraintViolation<T>> iterator = constraintViolations.iterator();
            while (iterator.hasNext()) {
                ConstraintViolation<T> violation = iterator.next();
                errMessage.append(violation.getPropertyPath()).append("：").append(violation.getMessage()).append("：");
            }
            logger.warn("表单校验失败：{}", errMessage.toString());
            return errMessage.toString();
        }
        logger.info("表单校验通过");
        return null;

    }

}
